﻿using Framework.Core.JsonSerialization.Extensions;
using Framework.Core.JsonSerialization.Providers;
using Framework.Core.Startup;
using Framework.DynamicApiController;
using Framework.WebApi.Swagger;
using Framework.WebApi.UnifyResult;
using Microsoft.AspNetCore.Builder;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Panda.DynamicWebApi;
using static NewLife.Remoting.ApiHttpClient;

namespace Framework.WebApi
{
	public class WebApiStartup : StartupModule<WebApiStartup>
	{
		/// <summary>
		/// Web Api 基础功能的注册
		/// </summary>
		public WebApiStartup() => Order = -1;

		public override void ConfigureServices(WebApplicationBuilder webApplicationBuilder)
		{
			webApplicationBuilder.Services.AddDynamicWebApiCore<ServiceLocalSelectController, ServiceActionRouteFactory>(); // 动态Api自定义配置
			webApplicationBuilder.Services.AddSwagger();        // 添加规范化文档服务
			webApplicationBuilder.Services.AddUnifyResult();    // 添加统一结果规范
		}

		public override void Configure(WebApplication webApplication)
		{
			// 添加动态接口控制器服务
			webApplication.UseDynamicWebApi((serviceProvider, options) =>
			{
				var dynamicWebApiOptions = App.GetConfig<DynamicWebApiOptions>("DynamicWebApiOptions");

				if(dynamicWebApiOptions.DefaultApiPrefix != null && dynamicWebApiOptions.DefaultApiPrefix.Length > 0)
				{
					// 指定全局默认的 api 前缀
					options.DefaultApiPrefix = dynamicWebApiOptions.DefaultApiPrefix;
				}

				// 清空API结尾，不删除API结尾;若不清空 CreatUserAsync 将变为 CreateUser
				options.RemoveActionPostfixes.Clear();

				// 自定义 ActionName 处理函数;
				options.GetRestFulActionName = (actionName) => actionName;

				// 添加所有程序集
				var assemblyList = AssemblyUtil.GetAssemblyList().ToList();
				foreach (var assembly in assemblyList)
				{
					options.AddAssemblyOptions(assembly);
				}
			});

			webApplication.UseSwaggerWeb(); // 添加规范化文档中间件
		}
	}
}
